/*
* @Author: ylq
 * @Date: 2021-08-23 18:57:12
 * @Desc: 导出文件
 * @Last Modified by: ylq
 * @Last Modified time: 2022-04-22 10:10:20
 */
const fs = require('fs')
const path = require('path')
const prettier = require('prettier')
const _ = require('lodash')

class ExportFiles {
  static compsPath = './src/components'
  static servicesPath = './src/api'
  static viewsPath = './src/views'
  static prettierPath = './.prettierrc'
  
  async start() {
    this.args = [...process.argv.slice(2)]
    if (this.getFlagOption('--c')) {
      this.exportComps()
    } else if (this.getFlagOption('--p')) {
      this.exportViews()
    } else if (this.getFlagOption('--s')) {
      this.exportServices()
    } else {
      this.exportComps()
      this.exportViews()
      this.exportServices()
    }
  }

  async exportComps() {
    const imports = []
    const exports = []
    const comps = fs.readdirSync(ExportFiles.compsPath).filter(value => value !== 'index.js')
    comps.forEach(compName => {
      let c = _.upperFirst(_.camelCase(compName))
      // console.log(38,compName)
      imports.push(`import ${c} from './${compName}/${compName}.vue'`)
      exports.push(`${c}`)
    })
    const templates = imports.join('\n') + '\n\n' + `export { ${exports.join(', ')} }`
    const formattedFile = await this.formatter(templates)
    fs.writeFileSync(path.join(ExportFiles.compsPath, './index.js'), formattedFile)
  }

  async exportViews() {
    const imports = []
    const exports = []
    const comps = fs.readdirSync(ExportFiles.viewsPath).filter(value => value !== 'index.js')
    comps.forEach(compName => {
      let c = _.upperFirst(_.camelCase(compName))
      imports.push(`const ${c} = tools.lazy(() => import('./${compName}/${compName}.vue'))`)
      // imports.push(`const ${compName} = r => require.ensure([], () => r(require('./${compName}/${compName}.vue')), ${compName.toLocaleLowerCase()})`)
      exports.push(`${c}`)
    })
    const templates =`import { tools } from '@/utils/tools'\n\n` + imports.join('\n') + '\n\n' + `export { ${exports.join(', ')} }`
    const formattedFile = await this.formatter(templates)
    fs.writeFileSync(path.join(ExportFiles.viewsPath, './index.js'), formattedFile)
  }

  async exportServices() {
    const imports = []
    const exports = []
    const files = fs
      .readdirSync(ExportFiles.servicesPath)
      .filter(value => value !== 'index.js' && value !== 'base-service.js')
    files.forEach(name => {
      const fileName = name.split('.')[0]
      let c = _.upperFirst(_.camelCase(fileName))
      const serviceName = c
        .split('')
        .map((value, index) => (index === 0 ? value.toLocaleLowerCase() : value))
        .join('')
      console.log(76,fileName)
      console.log(76,fileName,c,serviceName)
      imports.push(`import { ${serviceName} } from './${fileName}'`)
      exports.push(serviceName)
    })
    const templates = imports.join('\n') + '\n\n' + `export { ${exports.join(', ')} }`
    const formattedFile = await this.formatter(templates)
    fs.writeFileSync(path.join(ExportFiles.servicesPath, './index.js'), formattedFile)
  }

  async formatter(text) {
    const options = await prettier.resolveConfig(ExportFiles.prettierPath)
    const template = '// 此文件是自动生成的,不可手动修改此文件!编辑此文件请使用 yarn cc | cp | cs 命令'
    return prettier.format(template + '\n\n' + text, { ...options, parser: 'babel' })
  }

  getFlagOption(name) {
    const args = this.args

    if (name.startsWith('--')) {
      name = name.slice(2)
    }
    const fullName = `--${name}`
    for (const str of args) {
      if (str === fullName) {
        return true
      }
    }
    return false
  }
}

new ExportFiles().start()